package com.example.experiment4.web.client;

import com.example.experiment4.model.ResponseData.ArticleResponseData;
import com.example.experiment4.model.domain.Comment;
import com.example.experiment4.service.ICommentService;
import com.example.experiment4.utils.MyUtils;
import com.vdurmont.emoji.EmojiParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;

import java.util.Date;

@Controller
@RequestMapping("/comments")
@Api(tags = "Comment Controller", description = "评论相关操作接口")  // 整体描述这个Controller的功能
public class CommentController {
    private static final Logger logger = LoggerFactory.getLogger(CommentController.class);
    @Autowired
    private ICommentService commentServiceImpl;

    // 发表评论操作
    @PostMapping(value = "/publish")
    @ResponseBody
    @ApiOperation("发表评论操作接口")  // 描述这个接口方法的作用
    @ApiImplicitParams({
            @ApiImplicitParam(name = "aid", value = "文章ID", required = true),  // 对请求参数aid进行说明
            @ApiImplicitParam(name = "text", value = "评论内容", required = true)  // 对请求参数text进行说明
    })
    public ArticleResponseData publishComment(HttpServletRequest request, @RequestParam("aid") Integer aid, @RequestParam("text") String text) {
        // 去除js脚本
        text = MyUtils.cleanXSS(text);
        text = EmojiParser.parseToAliases(text);
        // 获取当前登录用户
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        // 封装评论信息
        Comment comment = new Comment();
        comment.setArticleId(aid);
        comment.setIp(request.getRemoteAddr());
        comment.setCreated(new Date());
        comment.setAuthor(user.getUsername());
        comment.setContent(text);
        try {
            commentServiceImpl.pushComment(comment);
            logger.info("发表评论成功，对应文章id：" + aid);
            return ArticleResponseData.ok();
        } catch (Exception e) {
            logger.error("发布评论失败，对应文章id: " + aid + ";错误描述: " + e.getMessage());
            return ArticleResponseData.fail();
        }
    }
}